import { defineConfig, loadEnv } from 'vite'
import path from 'path'
import createVitePlugins from './vite/plugins'
import { terser } from 'rollup-plugin-terser'

export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd())
  const {
    VITE_GLOB_API_URL,
    VITE_APP_BASE_API,
    VITE_GLOB_API_URL_PREFIX,
    VITE_ORDER_APP_BASE_API
  } = env
  const isBuild = env.VITE_APP_ENV === 'production'
  console.log({ isBuild })

  console.log('env', env)
  return {
    base: './',
    plugins: [
      createVitePlugins(env, isBuild),
      ...(isBuild ? [terser({ compress: { drop_console: true } })] : [])
    ],
    resolve: {
      alias: {
        '~': path.resolve(__dirname, './'),
        '@': path.resolve(__dirname, './src')
      },
      extensions: ['.mjs', '.js', '.jsx', '.json', '.vue']
    },

    // vite 相关配置
    define: {},
    server: {
      proxy: {
        [VITE_ORDER_APP_BASE_API]: {
          target: VITE_APP_BASE_API,
          changeOrigin: true,
          rewrite: (p) => p.replace(`${VITE_ORDER_APP_BASE_API}`, '')
        }
      },
      host: '0.0.0.0'
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/assets/styles/main.scss";',
          javascriptEnabled: true
        }
      },
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove()
                }
              }
            }
          }
        ]
      }
    },
    build: {
      // sourcemap: true,
      chunkSizeWarningLimit: 500, // chunk 大小警告的限制
      // 将打包的资源划分到不同的文件夹下
      rollupOptions: {
        output: {
          chunkFileNames: 'js/[name]-[hash].js', // 引入文件名的名称
          entryFileNames: 'js/[name]-[hash].js', // 包的入口文件名称
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]', // 资源文件像 字体，图片等
          experimentalMinChunkSize: 10 * 1024, // 合并小chunk
          // 主动拆分打包,创建自定义的公共 chunk -- https://cn.rollupjs.org/configuration-options/#output-manualchunks
          manualChunks(id) {
            if (id.includes('lodash')) {
              return 'lodash'
            }
            if (id.includes('@vue')) {
              return '@vue-vendor'
            }
            if (id.includes('echart')) {
              return 'echart'
            }
            if (id.includes('jsencrypt') || id.includes('axios')) {
              return 'request-vendor'
            }
            if (id.includes('element-plus')) {
              return 'element-plus'
            }
            if (id.includes('/node_modules/')) {
              return 'vendor'
            }
          }
        },
        treeshake: {
          preset: 'recommended',
          manualPureFunctions: ['console.log', 'console.error', 'console.warn']
        }
      },
      // 去除debugger 和 console
      esbuild: {
        drop: isBuild ? ['console', 'debugger'] : []
      }
    },
    optimizeDeps: {
      entries: ['/index.html']
    }
  }
})
